package Classic150;

import Tree.TreeNode;

import java.util.HashMap;
import java.util.Map;

public class 从中序与后序遍历序列构造二叉树 {
    /*
        递归，使用hashmap快速找到索引
     */
    Map<Integer, Integer> map = new HashMap<>();

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        for (int i = 0; i < inorder.length; i++) map.put(inorder[i], i);
        return findNode(0, postorder, 0, postorder.length);
    }

    private TreeNode findNode(int inBegin, int[] postorder, int postBegin, int postEnd) {
        if (postBegin == postEnd) return null;
        int rootValue = postorder[postEnd - 1];
        int rootIndex = map.get(rootValue);
        TreeNode root = new TreeNode(rootValue);
        int lenOfLeft = rootIndex - inBegin;
        root.left = findNode(inBegin, postorder, postBegin, postBegin + lenOfLeft);
        root.right = findNode(rootIndex + 1, postorder, postBegin + lenOfLeft, postEnd - 1);
        return root;
    }
}
